package com.ruoyi.contract.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ice.common.model.IceShowNode;
import com.ice.common.model.LeafNodeInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.contract.domain.*;
import com.ruoyi.contract.service.ConRuleService;
import com.ruoyi.contract.service.IceConfService;
import com.ruoyi.contract.mapper.IceConfMapper;
import com.ruoyi.contract.service.IceResultService;
import com.ruoyi.ice.domain.IceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 姚煜峰
* @description 针对表【ice_conf】的数据库操作Service实现
* @createDate 2023-07-10 11:33:13
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class IceConfServiceImpl extends ServiceImpl<IceConfMapper, IceConf> implements IceConfService {

    @Value("${other.ice.url}")
    private String iceUrl;

    @Value("${ice.app}")
    private String iceApp;

    final String iceEditUrl = "/ice-server/conf/edit";

    final String iceReleaseUrl = "/ice-server/conf/release";

    final String iceCleanUrl = "/ice-server/conf/update_clean";

    @Autowired
    IceResultService iceResultService;

    @Autowired
    ConRuleService conRuleService;

    @Override
    public boolean insertFlow(IceConf conf, IceFlow flow, ConRule rule) throws Exception {
        if(StringUtils.isNull(flow)){
            throw new Exception("判断节点不存在");
        }

        String dataBaseName = flow.getDatabaseName();//数据库名称

        String confType = flow.getConfType();//String Number Date

        String confName = flow.getConfName();//包名

        conf.setConfName(confName);

        Map<String,Object> map = new HashMap<>();

        if(ConfTypeEnum.String.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("string",conf.getFlowValue().replace("，",","));

        }

        if(ConfTypeEnum.Number.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("score",conf.getFlowValue());

        }

        if(ConfTypeEnum.Date.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("dateStr",conf.getFlowValue());

        }

        String json = JSONObject.toJSONString(map);



        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("confName",confName);
        requestMap.put("editType",1);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("nodeType",5);
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("confField",json);
        requestMap.put("inverse",conf.getInverse());

        requestMap.put("debug",1);





        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return true;
    }

    @Override
    public boolean insertRelation(IceConf conf, ConRule rule) throws Exception {

        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("editType",1);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("nodeType",conf.getType());

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return true;
    }

    @Override
    public boolean saveResult(IceConf conf, ConRule rule) throws Exception {

        if(StringUtils.isEmpty(conf.getResultType())){
            throw new Exception("计费方法不能为空");
        }

        if(StringUtils.isNull(conf.getUnitPrice())){
            throw new Exception("单价不能为空");
        }

        Map<String,Object> map = new HashMap<>();

        Map<String,Object> requestMap = new HashMap<>();

        if(ConfTypeEnum.Amount.getCode().equals(conf.getResultType())){

            //拼接 AmountResult 的 confField
            map.put("value",conf.getUnitPrice());

            if(StringUtils.isNull(conf.getWorkNumId())&&StringUtils.isNull(conf.getWorkDaysId())){
                throw new Exception("请选择至少一个计费字段");
            }

            if(StringUtils.isNotNull(conf.getWorkNumId())){

                IceResult result = iceResultService.getById(conf.getWorkNumId());

                if(StringUtils.isNull(result)){
                    throw new Exception("计费字段1不存在");
                }

                map.put("workWeightKey",result.getDatabaseName());

            }

            if(StringUtils.isNotNull(conf.getWorkDaysId())){

                IceResult result = iceResultService.getById(conf.getWorkDaysId());

                if(StringUtils.isNull(result)){
                    throw new Exception("计费字段2不存在");
                }

                map.put("workDaysKey",result.getDatabaseName());

            }

            requestMap.put("confName",ConfTypeEnum.Amount.getInfo());

        }else if (ConfTypeEnum.Ladder.getCode().equals(conf.getResultType())){

            //if(StringUtils.isNull(conf.getWorkNumId())||StringUtils.isNull(conf.getLadderDaysId())){
            //    throw new Exception("计费字段不能为空");
            //}

            if(StringUtils.isNull(conf.getWorkNumId())&&StringUtils.isNull(conf.getWorkDaysId())){
                throw new Exception("请选择至少一个计费字段");
            }

            map.put("value",conf.getUnitPrice());

            if(StringUtils.isNotNull(conf.getWorkNumId())){

                IceResult result = iceResultService.getById(conf.getWorkNumId());

                //if(StringUtils.isNull(result)){
                //    throw new Exception("计费字段1不存在");
                //}
                if(StringUtils.isNotNull(result)){
                    map.put("workWeightKey",result.getDatabaseName());
                }


            }

            if(StringUtils.isNotNull(conf.getLadderDaysId())){

                IceResult result = iceResultService.getById(conf.getLadderDaysId());

                if(StringUtils.isNull(result)){
                    throw new Exception("阶梯计费字段不存在");
                }

                map.put("workDaysKey",result.getDatabaseName());

            }

            if(StringUtils.isNull(conf.getMinValue())&&StringUtils.isNull(conf.getMaxValue())){
                throw new Exception("阶梯计费最大值和最小值不能同时为空");
            }

            if(StringUtils.isNotNull(conf.getMinValue())){
                map.put("minValue",conf.getMinValue());
            }

            if(StringUtils.isNotNull(conf.getMaxValue())){
                map.put("maxValue",conf.getMaxValue());
            }
            requestMap.put("confName",ConfTypeEnum.Ladder.getInfo());
        }else {
            throw new Exception("结果类型不存在");
        }

        String json = JSONObject.toJSONString(map);

        requestMap.put("app",iceApp);
        requestMap.put("editType",1);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("nodeType",6);
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("confField",json);
        requestMap.put("inverse",conf.getInverse());

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return true;
    }

    @Override
    public AjaxResult remove(IceEditNode node) throws Exception {


        if(StringUtils.isNull(node.getRuleId())){
            return AjaxResult.error("请选择规则");
        }

        if(StringUtils.isNull(node.getSelectId())){
            throw new Exception("请选择要删除的节点");
        }

        ConRule rule = conRuleService.getById(node.getRuleId());

        if(StringUtils.isNull(rule)){
            return AjaxResult.error("规则不存在");
        }

        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("editType",3);

        requestMap.put("selectId",node.getSelectId());
        if(StringUtils.isNotNull(node.getParentId())){
            requestMap.put("parentId",node.getParentId());
        }
        if(StringUtils.isNotNull(node.getIndex())){
            requestMap.put("index",node.getIndex());
        }
        if(StringUtils.isNotNull(node.getNextId())){
            requestMap.put("nextId",node.getNextId());
        }

        requestMap.put("iceId",rule.getIceId());

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return AjaxResult.success();
    }

    @Override
    public boolean exchangeRelation(IceConf conf, ConRule rule) throws Exception {

        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("app",iceApp);

        requestMap.put("editType",5);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("nodeType",conf.getType());
        requestMap.put("index",conf.getIndex());
        requestMap.put("parentId",conf.getParentId());
        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }
        return true;
    }

    @Override
    public boolean exchangeFlow(IceConf conf, IceFlow flow, ConRule rule) throws Exception {
        if(StringUtils.isNull(flow)){
            throw new Exception("判断节点不存在");
        }

        String dataBaseName = flow.getDatabaseName();//数据库名称

        String confType = flow.getConfType();//String Number Date

        String confName = flow.getConfName();//包名

        conf.setConfName(confName);

        Map<String,Object> map = new HashMap<>();

        if(ConfTypeEnum.String.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("string",conf.getFlowValue().replace("，",","));

        }

        if(ConfTypeEnum.Number.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("score",conf.getFlowValue());

        }

        if(ConfTypeEnum.Date.getCode().equals(confType)){

            map.put("key",dataBaseName);
            map.put("dateStr",conf.getFlowValue());

        }

        String json = JSONObject.toJSONString(map);



        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("confName",confName);
        requestMap.put("editType",5);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("nodeType",5);
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("confField",json);
        requestMap.put("inverse",conf.getInverse());

        requestMap.put("debug",1);

        requestMap.put("index",conf.getIndex());
        requestMap.put("parentId",conf.getParentId());






        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return true;
    }

    @Override
    public boolean exchangeResult(IceConf conf, ConRule rule) throws Exception {
        if(StringUtils.isEmpty(conf.getResultType())){
            throw new Exception("计费方法不能为空");
        }

        if(StringUtils.isNull(conf.getUnitPrice())){
            throw new Exception("单价不能为空");
        }

        Map<String,Object> map = new HashMap<>();

        Map<String,Object> requestMap = new HashMap<>();

        if(ConfTypeEnum.Amount.getCode().equals(conf.getResultType())){

            //拼接 AmountResult 的 confField
            map.put("value",conf.getUnitPrice());

            if(StringUtils.isNull(conf.getWorkNumId())&&StringUtils.isNull(conf.getWorkDaysId())){
                throw new Exception("请选择至少一个计费字段");
            }

            if(StringUtils.isNotNull(conf.getWorkNumId())){

                IceResult result = iceResultService.getById(conf.getWorkNumId());

                if(StringUtils.isNull(result)){
                    throw new Exception("计费字段1不存在");
                }

                map.put("workWeightKey",result.getDatabaseName());

            }

            if(StringUtils.isNotNull(conf.getWorkDaysId())){

                IceResult result = iceResultService.getById(conf.getWorkDaysId());

                if(StringUtils.isNull(result)){
                    throw new Exception("计费字段2不存在");
                }

                map.put("workDaysKey",result.getDatabaseName());

            }

            requestMap.put("confName",ConfTypeEnum.Amount.getInfo());

        }else if (ConfTypeEnum.Ladder.getCode().equals(conf.getResultType())){

            //if(StringUtils.isNull(conf.getWorkNumId())||StringUtils.isNull(conf.getLadderDaysId())){
            //    throw new Exception("计费字段不能为空");
            //}

            if(StringUtils.isNull(conf.getWorkNumId())&&StringUtils.isNull(conf.getWorkDaysId())){
                throw new Exception("请选择至少一个计费字段");
            }

            map.put("value",conf.getUnitPrice());

            if(StringUtils.isNotNull(conf.getWorkNumId())){

                IceResult result = iceResultService.getById(conf.getWorkNumId());

                //if(StringUtils.isNull(result)){
                //    throw new Exception("计费字段1不存在");
                //}


                if(StringUtils.isNotNull(result))
                    map.put("workWeightKey",result.getDatabaseName());

            }

            if(StringUtils.isNotNull(conf.getLadderDaysId())){

                IceResult result = iceResultService.getById(conf.getLadderDaysId());

                if(StringUtils.isNull(result)){
                    throw new Exception("阶梯计费字段不存在");
                }

                map.put("workDaysKey",result.getDatabaseName());

            }

            if(StringUtils.isNull(conf.getMinValue())&&StringUtils.isNull(conf.getMaxValue())){
                throw new Exception("阶梯计费最大值和最小值不能同时为空");
            }

            if(StringUtils.isNotNull(conf.getMinValue())){
                map.put("minValue",conf.getMinValue());
            }

            if(StringUtils.isNotNull(conf.getMaxValue())){
                map.put("maxValue",conf.getMaxValue());
            }
            requestMap.put("confName",ConfTypeEnum.Ladder.getInfo());
        }else {
            throw new Exception("结果类型不存在");
        }

        String json = JSONObject.toJSONString(map);

        requestMap.put("app",iceApp);
        requestMap.put("editType",5);
        requestMap.put("iceId",rule.getIceId());
        requestMap.put("name",conf.getName());
        requestMap.put("nodeType",6);
        requestMap.put("selectId",conf.getSelectId());
        requestMap.put("confField",json);
        requestMap.put("inverse",conf.getInverse());

        requestMap.put("index",conf.getIndex());
        requestMap.put("parentId",conf.getParentId());

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return true;
    }

    @Override
    public AjaxResult edit(IceShowNode node, Long iceId) throws Exception {

        if(StringUtils.isNull(iceId)){
            throw new Exception("iceId不能为空");
        }

        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("iceId",iceId);
        requestMap.put("editType",2);

        IceShowNode.NodeShowConf showConf = node.getShowConf();

        requestMap.put("selectId",showConf.getNodeId());

        requestMap.put("debug",showConf.getDebug());
        requestMap.put("inverse",showConf.getInverse());

        requestMap.put("name",showConf.getNodeName());

        requestMap.put("nodeType",showConf.getNodeType());

        requestMap.put("confName",showConf.getConfName());

        //requestMap.put("haveMeta",showConf.getHaveMeta());
        //
        //requestMap.put("updating",true);

        //requestMap.put("uniqueKey",showConf.getUniqueKey());
        //
        //requestMap.put("parentId",node.getParentId());

        Map<String,Object> map = new HashMap<>();

        if(StringUtils.isNotNull(showConf.getNodeInfo().getIceFields())){

            List<LeafNodeInfo.IceFieldInfo> iceFields = showConf.getNodeInfo().getIceFields();

            for(LeafNodeInfo.IceFieldInfo iceField : iceFields){

                if("java.lang.String".equals(iceField.getType())){
                    map.put(iceField.getField(),String.valueOf(iceField.getValue()).replace("，",","));
                }else {
                    map.put(iceField.getField(),iceField.getValue());
                }


            }
        }

        if(StringUtils.isNotNull(showConf.getNodeInfo().getHideFields())){
            List<LeafNodeInfo.IceFieldInfo> hideFields = showConf.getNodeInfo().getHideFields();

            for(LeafNodeInfo.IceFieldInfo iceField : hideFields){

                if("java.lang.String".equals(iceField.getType())){
                    map.put(iceField.getField(),String.valueOf(iceField.getValue()).replace("，",","));
                }else {
                    map.put(iceField.getField(),iceField.getValue());
                }

                //map.put(iceField.getField(),iceField.getValue());
            }
        }

        String json = JSONObject.toJSONString(map);

        requestMap.put("confField",json);

        requestMap.put("timeType",StringUtils.isNotNull(node.getTimeType())?node.getTimeType():1);

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult release(Long iceId) throws Exception {

        if(StringUtils.isNull(iceId)){
            return AjaxResult.error("iceId不能为空");
        }

        String url = iceUrl + iceReleaseUrl + "?app=" + iceApp + "&iceId=" + iceId;

        RestTemplate restTemplate = new RestTemplate();

        IceResponse iceResponse = restTemplate.getForObject(url,IceResponse.class);

        Long ret = iceResponse.getRet();

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult clean(Long iceId) throws Exception {
        if(StringUtils.isNull(iceId)){
            return AjaxResult.error("iceId不能为空");
        }

        String url = iceUrl + iceCleanUrl + "?app=" + iceApp + "&iceId=" + iceId;

        RestTemplate restTemplate = new RestTemplate();

        IceResponse iceResponse = restTemplate.getForObject(url,IceResponse.class);

        Long ret = iceResponse.getRet();

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult move(IceEditNode node) throws Exception {

        if(StringUtils.isNull(node.getIceId())){
            return AjaxResult.error("iceId不能为空");
        }

        if(StringUtils.isNull(node.getSelectId())){
            return AjaxResult.error("selectId不能为空");
        }

        if(StringUtils.isNull(node.getParentId())){
            return AjaxResult.error("parentId不能为空");
        }

        if(StringUtils.isNull(node.getMoveToParentId())){
            return AjaxResult.error("moveToParentId不能为空");
        }

        if(StringUtils.isNull(node.getIndex())){
            return AjaxResult.error("index不能为空");
        }

        if(StringUtils.isNull(node.getMoveTo())){
            return AjaxResult.error("moveToIndex不能为空");
        }

        Map<String,Object> requestMap = new HashMap<>();

        requestMap.put("app",iceApp);
        requestMap.put("editType",6);

        requestMap.put("iceId",node.getIceId());

        requestMap.put("selectId",node.getSelectId());

        requestMap.put("parentId",node.getParentId());

        requestMap.put("moveToParentId",node.getMoveToParentId());

        requestMap.put("index",node.getIndex());

        requestMap.put("moveTo",node.getMoveTo());

        Long ret = Long.valueOf(editConf(requestMap).toString());

        if(ret != 0){
            throw new Exception("ice服务异常");
        }

        return AjaxResult.success();
    }

    public Object editConf(Map<String,Object> map ) throws Exception {

        RestTemplate restTemplate = new RestTemplate();

        String url = iceUrl + iceEditUrl;

        System.out.println(url);

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_JSON);

        System.out.println(map);

        HttpEntity<Map<String,Object>> request = new HttpEntity<>(map,headers);

        IceResponse iceResponse = restTemplate.postForEntity(url,request,IceResponse.class).getBody();

        if(StringUtils.isNull(iceResponse)){
            throw new Exception("ice服务异常");
        }

        System.out.println(iceResponse);

        return iceResponse.getRet();
    }

}




